using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CheckpointLane : MonoBehaviour
{
    Color color;

    // Start is called before the first frame update
    void Start()
    {
        var colors = new[] { Color.red, Color.magenta, Color.yellow };
        SetColor(colors[Random.Range(0, colors.Length)]);
    }

    // Update is called once per frame
    void Update()
    {
        var res = FindObjectsOfType<Package>()
             .Select(o => new { Obj = o, Distance = o.transform.position - transform.position })
             .Where(o => Mathf.Abs(o.Distance.x) < 0.4f && Mathf.Abs(o.Distance.z) < 3);
        var controlledPackage = res.Where(o => o.Obj.gameObject == GameManager.ControlledObject);
        res = res.Where(o => o.Obj.color == color);

        foreach (var package in res)
        {
            SFXEmitter.PlayDeploySound();
            GameManager.Current.Score++;
            Destroy(package.Obj.gameObject);
        }

        foreach (var package in controlledPackage)
        {
            if (package.Obj.color == color)
            {
                GameManager.Current.Release();
                SFXEmitter.PlayDeploySound();
                GameManager.Current.Score++;
                Destroy(package.Obj.gameObject);
            }
            else
            {
                print("killed");
                //kill
            }
        }
    }

    public void SetColor(Color c)
    {
        color = c;
        GetComponent<Renderer>().material = GameManager.Current.Colors[c];
    }
}
